<template>
  <!-- 分配权限的弹层 -->
  <el-dialog
    title="分配权限(一级为路由页面查看权限-二级为按钮操作权限)"
    :visible="showAssignDialog"
    @close="closeAssignDialog"
  >
    <!-- 权限点数据展示 -->
    <el-tree
      ref="tree"
      :data="permList"
      default-expand-all
      :props="{ label: 'name' }"
      show-checkbox
      check-strictly
      node-key="id"
    />
    <template #footer>
      <el-button @click="closeAssignDialog">取消</el-button>
      <el-button type="primary" @click="assignPerm">确定</el-button>
    </template>
  </el-dialog>
</template>

<script>
import { getPermissionList } from '@/api/permission'
import { tranformTreeData } from '@/utils'
import { getRoleDetail, assignPerm } from '@/api/setting'
export default {
  props: {
    showAssignDialog: {
      type: Boolean,
      default: false
    }
  },
  data () {
    return {
      permList: [],
      // 角色id
      roleId: ''
    }
  },
  created () {
    this.getList()
  },
  methods: {
    // 确认添加权限
    async assignPerm () {
      try {
        await assignPerm({ id: this.roleId, permIds: this.$refs.tree.getCheckedKeys() })
        this.$emit('update:showAssignDialog', false)
        this.$message.success('添加权限成功')
      } catch (error) {
        console.log(error)
      }
    },
    // 获取已经有的权限点，数据回显
    async getAssignPerm (id) {
      const { permIds } = await getRoleDetail(id)
      this.$refs.tree.setCheckedKeys(permIds)
      this.roleId = id
    },
    // 获取列表数据
    async getList () {
      const res = await getPermissionList()
      this.permList = tranformTreeData(res)
    },
    // 关闭对话框
    closeAssignDialog () {
      this.$emit('update:showAssignDialog', false)
    }
  }
}
</script>

<style lang="scss" scoped>
</style>
